﻿/*
 * Created by SharpDevelop.
 * User: Jobe
 * Date: 04.10.2006
 * Time: 20:24
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Threading;
using System.Windows.Forms;

using Microsoft.Win32;

	//debug, etc.


namespace LauncherPlus
{
	
	public partial class FormMain
	{
				
		public System.Resources.ResourceSet Resources = null;
		public PlugIn.AppSettings Settings = null;
		public cGame Game = null;
		public System.Collections.Hashtable CommandLine = null;

		private FormOptions Options = null;
		private AppSettingsSection app = null;
		private AppSettingsSection wow = null;
		private static FormMain LauncherPlusMain = null;
		
		[STAThread]
		public static void Main(string[] args)
		{
			try {
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				bool isFirstInstance;
				// Please use a unique name for the mutex to prevent conflicts with other programs
				using (Mutex mtx = new Mutex(true, "LauncherPlus", out isFirstInstance)) {
					if (isFirstInstance) {
						LauncherPlusMain = new FormMain(args);
						Application.Run(LauncherPlusMain);
					} else {
						// The application is already running
						MessageBox.Show("...is already running!","LauncherPlus");
					}
				} // releases the Mutex
				// save main form instanz in static field for further access
			} catch (Exception ex) {
				DirectoryInfo Desktop = new DirectoryInfo(System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory));
				FileInfo LogFile = new FileInfo(Desktop.FullName+"/LauncherPlus"+System.DateTime.Now.ToString("yyyyMMddHHmmss")+".log");
				StreamWriter LogFileStream = LogFile.CreateText();
				LogFileStream.Write(ex.ToString());
				LogFileStream.Close();
				Debug.WriteLine(ex.ToString());
				MessageBox.Show("There has been an error.\n\nPlease mail generated log files in your installation folder to:\t\n\n\tjobe@jobesoft.de\t\n\nThank you for your support!","Sorry ...");
			}/**/
		}

		#region Form

		public FormMain(string[] args)
		{
			
			InitializeComponent();
			
			Game = new cGame();
			
			CommandLine = new Hashtable();
			
			ParseCommandLine(args);
			
			// load configuration file
			Settings = new PlugIn.AppSettings("LauncherPlus");
			app = Settings.GetAppSettingsSection("appSettings");
			wow = Settings.GetAppSettingsSection("wowSettings");

			// load resource file
			FileInfo ResFile = new FileInfo(Application.StartupPath + "/lang[EN].resources");
			if(ResFile.Exists){
				this.Resources = new ResourceSet(ResFile.FullName);
			}else{
				throw new Exception("Couldn't find resource file");
			}

			// create objects
			this.Options = new FormOptions(this);
			
			// set object properties
			this.webBrowser.Hide();
			this.labelPatchInfo.Hide();
			this.webBrowser.BringToFront();
			this.ButtonQuit.SendToBack();
			FormMainResize(this,null);
			try{
				this.LabelStatus.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BACK_MAIN"));
				this.labelPatchInfo.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BACK_PATCHINFO"));
				this.btnPlay.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PLAY_NORMAL"));
				this.btnSupport.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_SUPPORT_NORMAL"));
				this.btnOptions.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_OPTIONS_NORMAL"));
				this.btnPublicTest.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PUBLICTEST_NORMAL"));
				this.pbxBtnsBack.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BACK_BTNS_NORMAL"));
			}catch ( Exception ex ){
				throw new Exception("Main(104) : Couldn't load resources!\n\n"+ex.ToString());
			}

			// get wow-version
			string VersionA = Game.FileVersion;
			string VersionB = this.Settings.LoadSetting(this.wow,"WOWVersion");
			this.Text = Game.ProductName + " v" + VersionA;
			this.Settings.SaveSetting(this.wow,"WOWVersion",VersionA);

			// test start directory 
			RegistryKey appRegistry = Registry.CurrentUser.OpenSubKey("SOFTWARE\\LauncherPlus");
			if(appRegistry!=null){
				DirectoryInfo a = new DirectoryInfo((string)appRegistry.GetValue(""));
				DirectoryInfo b = new FileInfo(Application.ExecutablePath).Directory;
				if(!a.FullName.Equals(b.FullName))Text += " - " + b.FullName;
			}else{
				//throw new Exception("Application not properly installed. Please use installer.");
			}
			
		}

		void ParseCommandLine(string[] args){
			for( int i = 0 ; i < args.Length ; i++ ){
				if(args[i].StartsWith("-")){ // command
					switch(args[i].ToLower()){
						case "-debug":	CommandLine.Add("DEBUG",true); break;
						case "-plugin":	CommandLine.Add("PLUGIN",args[++i]); break;
					}
				}else{ // bwa-file
					this.CommandLine.Add("BWA",args[i]);
				}
			}
		}
		
		void FormMainLoad(object sender, System.EventArgs e)
		{
			Settings.LoadLayout( this.app, this );
			webBrowser.Tag = "Loading news ...";
			webBrowser.Hide();
			webBrowser.Navigate(Game.Locale[Game.ActiveLanguage].URL);
		}
		
		void FormFormMainClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
		{
			this.Settings.SaveLayout( this.app, this );
			this.Settings.Save();
		}

		void FormMainKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			try{

			}catch(Exception ex){
				Debug.WriteLine("FormMainKeyDown: "+ex.ToString());
			}
		}
		
		void FormMainResize(object sender, EventArgs e)
		{
			this.webBrowser.SetBounds(0,0,640,402);
			this.LabelStatus.SetBounds(0,0,640,402);
			this.labelPatchInfo.SetBounds(13,410,339,47);
			this.Height = SystemInformation.CaptionHeight + 486;
			this.pbxBtnsBack.Height = 78;
			this.btnPlay.Top = pbxBtnsBack.Top + 11;
			this.btnSupport.Top = pbxBtnsBack.Top + 36;
			this.btnOptions.Top = pbxBtnsBack.Top + 36;
			this.btnPublicTest.Top = pbxBtnsBack.Top + 36;
		}

		#endregion

		#region btnPlay
		
		void BtnPlayMouseEnter(object sender, System.EventArgs e)
		{
			this.btnPlay.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PLAY_HOVER"));
		}
			
		void BtnPlayMouseLeave(object sender, System.EventArgs e)
		{
			this.btnPlay.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PLAY_NORMAL"));
		}
		
		void BtnPlayMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnPlay.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PLAY_DOWN"));
		}
		
		void BtnPlayMouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnPlay.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PLAY_HOVER"));
		}

		void BtnPlayClick(object sender, System.EventArgs e)
		{
			string GuildURL = Settings.LoadSetting(wow,"GuildURL");
			if((GuildURL.Length>0)&&!webBrowser.Url.Equals(GuildURL)){
				webBrowser.Tag = "Loading guild news ...";
				webBrowser.Hide();
				webBrowser.Navigate(GuildURL);
			}else{
				Process myProc;
				FileInfo wowexe = new FileInfo( Game.InstallPath.FullName + "/WoW.exe" );
				if(wowexe.Exists){
					WindowState = FormWindowState.Minimized;	Application.DoEvents();//give time to execute
					webBrowser.Stop();							Application.DoEvents();//give time to execute
					webBrowser.Navigate("about:blank");			Application.DoEvents();//give time to execute
					webBrowser.Hide(); 							Application.DoEvents();//give time to execute
					myProc = Process.Start(wowexe.FullName);	Application.DoEvents();//give time to execute
					if( Settings.LoadSetting(wow,"RosterAutoUpload").Equals("True") ){
						myProc.WaitForExit();									Application.DoEvents();//give time to execute
						LabelStatus.Text = "Uploading data...";					Application.DoEvents();//give time to execute
						WindowState = FormWindowState.Normal;					Application.DoEvents();//give time to execute
						Options.ShowDialog();									Application.DoEvents();//give time to execute
						webBrowser.Navigate(GuildURL);	Application.DoEvents();//give time to execute
						if(Settings.LoadSetting(wow,"RosterAutoClose").Equals("True")){
							MessageBoxManager.HookEnabled = true;
							MessageBoxManager.TimeOut = 10;
							DialogResult r = MessageBox.Show("Auto-closing Launcher Plus ...","10 seconds remaining...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
							MessageBoxManager.HookEnabled = false;
							if(r.Equals(DialogResult.OK))Application.Exit();
						}
					}else{
						Application.Exit();
					}
				}else{
					MessageBox.Show("Couldn't find wow.exe.");
				}
			}
			webBrowser.Focus();
		}
		
		#endregion

		#region btnSupport
		
		void BtnSupportMouseEnter(object sender, System.EventArgs e)
		{
			this.btnSupport.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_SUPPORT_HOVER"));
		}
		
		void BtnSupportMouseLeave(object sender, System.EventArgs e)
		{
			this.btnSupport.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_SUPPORT_NORMAL"));
		}
		
		void BtnSupportMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnSupport.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_SUPPORT_DOWN"));
		}
		
		void BtnSupportMouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnSupport.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_SUPPORT_HOVER"));
		}

		void BtnSupportClick(object sender, System.EventArgs e)
		{
			try{
				/* http://www.wow-europe.com/de/support/ */
				Process.Start("http://www.wow-europe.com/de/support/");
			} catch (Exception ex) {
				MessageBox.Show("Couldn't load website.\n\n(" + ex.Message + ")");
			}
		}
		
		#endregion
		
		#region btnOptions
		
		void btnOptionsMouseEnter(object sender, System.EventArgs e)
		{
			this.btnOptions.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_OPTIONS_HOVER"));
		}
		
		void btnOptionsMouseLeave(object sender, System.EventArgs e)
		{
			if(!Options.Visible){
				this.btnOptions.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_OPTIONS_NORMAL"));
			}
		}
		
		void BtnOptionsClick(object sender, System.EventArgs e)
		{
			this.btnOptions.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_OPTIONS_DOWN"));
			Application.DoEvents();
			if(Options.ShowDialog(this) == DialogResult.OK){
			}
			this.btnOptions.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_OPTIONS_NORMAL"));
			Application.DoEvents();
		}

		#endregion

		#region btnPublicTest
		
		void btnPublicTestMouseEnter(object sender, System.EventArgs e)
		{
			this.btnPublicTest.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PUBLICTEST_HOVER"));
		}
		
		void btnPublicTestMouseLeave(object sender, System.EventArgs e)
		{
			this.btnPublicTest.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PUBLICTEST_NORMAL"));
		}
		
		void btnPublicTestMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnPublicTest.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PUBLICTEST_DOWN"));
		}
		
		void btnPublicTestMouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.btnPublicTest.BackgroundImage = ((System.Drawing.Image)this.Resources.GetObject("BTN_PUBLICTEST_HOVER"));
		}
		
		void BtnPublicTestClick(object sender, System.EventArgs e)
		{
			try{
				Process.Start("http://www.wow-europe.com/de/ptr/");
			} catch (Exception ex) {
				MessageBox.Show("Couldn't load website.\n\n(" + ex.Message + ")");
			}/* http://www.wow-europe.com/de/ptr/ */
		}
		
		#endregion

		#region ButtonQuit
		
		void ButtonQuitClick(object sender, System.EventArgs e)
		{
			Application.Exit();
		}

		#endregion
		
		#region webBrowser
		
		void WebBrowserNavigating(object sender, System.Windows.Forms.WebBrowserNavigatingEventArgs e)
		{
			Debug.WriteLine("Navigating to: "+e.Url.AbsoluteUri);
			string GuildURL = Settings.LoadSetting(wow,"GuildURL");
			string IsURL = e.Url.AbsoluteUri;
			// all URL except following redirect to standard browser
			// 1. "http://launcher.wow-europe.com/de/"
			// 2. "about:blank"
			// 3. guild url
			e.Cancel = false;
			e.Cancel |= e.Url.AbsoluteUri.Equals(Game.Locale[Game.ActiveLanguage].URL);
			e.Cancel |= e.Url.AbsoluteUri.Equals("about:blank");
			e.Cancel |= e.Url.AbsoluteUri.Equals(Settings.LoadSetting(wow,"GuildURL"));
			e.Cancel = !e.Cancel; // if no no match found cancel action 
			if(e.Cancel)Process.Start(e.Url.AbsoluteUri);
		}
		
		void WebBrowserDocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
		{
			if(!webBrowser.Visible)WebBrowserInvokeScript("OnDocumentShown");
			webBrowser.Show();
		}
		
		void WebBrowserInvokeScript(string ScriptName)
		{
			WebBrowserInvokeScript(ScriptName,null);
		}
		
		void WebBrowserInvokeScript(string ScriptName, string[] args)
		{
		    if (webBrowser.Document!=null){
				try{
					if(args!=null){
				        webBrowser.Document.InvokeScript(ScriptName, args);
					}else{
				        webBrowser.Document.InvokeScript(ScriptName);
					}
				}catch(Exception ex){
					MessageBox.Show(this, "Failed to invoke script:\n\n" + ex.Message, "Browser operation failed", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				}
		    }
		}
		
		void WebBrowserNavigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)
		{
			WebBrowserDocumentCompleted(sender,null);
		}
		
		void WebBrowserProgressChanged(object sender, System.Windows.Forms.WebBrowserProgressChangedEventArgs e)
		{
			int Percent = (int)( e.CurrentProgress / e.MaximumProgress * 100 );
			LabelStatus.Text = ((string)webBrowser.Tag);
			LabelStatus.Text += "\n\n(" + Percent.ToString() + ")";
			LabelStatus.Text += "\n\n(" + e.CurrentProgress.ToString() + "/" + e.MaximumProgress.ToString() + ")";
			if(e.CurrentProgress>=e.MaximumProgress)WebBrowserDocumentCompleted(sender,null);
		}
		
		#endregion
	
		#region Help
		
		public void Help(){
			this.Help(1);
		}
		
		public void Help(int MapID){
			FileInfo HelpFile = new FileInfo(Application.StartupPath + "/LauncherPlus.chm");
			if(HelpFile.Exists){
				Process.Start("HH.EXE"," -mapid "+MapID.ToString()+" ms-its:"+HelpFile.FullName);
			}else{
				MessageBox.Show("Couldn't find help");
			}
		}
		
		#endregion

	}
}
